package com.wzm.moviepic.fragment;


import java.io.ByteArrayOutputStream;
import java.io.IOException;

import net.tsz.afinal.FinalBitmap;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SocializeClientListener;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.view.ActionBarView;
import com.wzm.bean.DownInfo;
import com.wzm.bean.MovieInfo;
import com.wzm.db.DBHelper;
import com.wzm.manager.AppConfig;
import com.wzm.manager.AppManager;
import com.wzm.manager.Tag;
import com.wzm.moviepic.AppApplication;
import com.wzm.moviepic.R;
import com.wzm.utils.Logger;
import com.wzm.utils.NetworkUtils;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class MovieIntroActivity extends Activity{
	private MovieInfo mi = null;
	
	private RatingBar rBar = null;
	private TextView movie_rate = null;
	private ImageView bPic = null;
	private TextView mIntro = null;
	private TextView mName = null;
	private TextView mAuthor =null;
	private TextView mActor = null;
	private TextView mShowTime = null;
	private LinearLayout btn_down = null;
	private LinearLayout btn_read = null;
	
	private Button btn_mback = null;
	
	private FinalBitmap fb = null;
	
	private Context mContext = null;
	
	private TextView tv_read = null;
	
	private LinearLayout rly_share = null;
	
	//手势
	private GestureDetector detector;
	private ScrollView sv = null;
	
    private int screen_width = 0;
    private int screen_height = 0;
    
    private int like = -1;
    private ImageView img_ding;
    private ImageView img_cai;
    
    //private int index = -1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_movie);
		
		Logger.error("onCreate");
		//if(AppApplication.getInstance().getfMap().containsKey(mi.getId()))
		
		mContext = this;
		
		detector = new GestureDetector(this,new OnGestureListener() {
			
			@Override
			public boolean onSingleTapUp(MotionEvent e) {
				// TODO Auto-generated method stub
				return false;
			}
			
			@Override
			public void onShowPress(MotionEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
					float distanceY) {
				// TODO Auto-generated method stub
				return false;
			}
			
			@Override
			public void onLongPress(MotionEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
					float velocityY) {
				// TODO Auto-generated method stub
				
				if (e1.getX() - e2.getX() > 120) {
					finish();
		            return true;
		        } else if (e1.getX() - e2.getX() < -120) {
		        	finish();
		            return true;
		        }
				
				return false;
			}
			
			@Override
			public boolean onDown(MotionEvent e) {
				// TODO Auto-generated method stub
				return false;
			}
		});

		
		mi = (MovieInfo)getIntent().getSerializableExtra("movieinfo");
		if(mi==null)
		{
			Toast.makeText(this, "参数传递错误，请下载最新版本", Toast.LENGTH_SHORT).show();
			return;
		}
		
		Logger.info("电影："+mi.getName());
		sv = (ScrollView)findViewById(R.id.scrollView1);
		sv.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				return detector.onTouchEvent(event);
			}
		});
		fb = FinalBitmap.create(this,Environment.getExternalStorageDirectory().getPath()+AppConfig.IMGCACHE);
		fb.configLoadingImage(R.drawable.topwnd_default);
		fb.configLoadfailImage(R.drawable.topwnd_default);		
		bPic = (ImageView)findViewById(R.id.movie_bpic);
		
		
		DisplayMetrics dm = new DisplayMetrics();  
        getWindowManager().getDefaultDisplay().getMetrics(dm);  
        screen_width = dm.widthPixels;  
		screen_height = dm.heightPixels;
		
		//ad_img
		//动态改变图片控件大小
		RelativeLayout.LayoutParams laParams=(RelativeLayout.LayoutParams)bPic.getLayoutParams();
		laParams.height=460*screen_width/640;
	    laParams.width=screen_width;
	    bPic.setLayoutParams(laParams);
		
		
	    //介绍
	    mIntro = (TextView)findViewById(R.id.movie_intro);
	    //名字
	  	mName = (TextView)findViewById(R.id.movie_name);
	  	//ratebar
	  	rBar = (RatingBar)findViewById(R.id.ratingBar);
	  	movie_rate = (TextView)findViewById(R.id.movie_rate);
	  	mAuthor = (TextView)findViewById(R.id.movie_author);
	  	mActor = (TextView)findViewById(R.id.movie_actor);
	  	mShowTime = (TextView)findViewById(R.id.movie_showtime);
	  	btn_down =(LinearLayout)findViewById(R.id.lly_down);
	  	btn_read = (LinearLayout)findViewById(R.id.lly_read);
	  	tv_read =(TextView)findViewById(R.id.tv_offread);
	  	
	  	
		
	  	
	  	
	  	fb.display(bPic, mi.getBpic(),640,460);		
		mIntro.setText(mi.getIntro());		
		mName.setText(mi.getName());		
		rBar.setRating(Float.parseFloat(mi.getScore()));		
		movie_rate.setText(mi.getScore());		
		mAuthor.setText(mi.getAuthor());		
		mActor.setText(mi.getActor());		
		mShowTime.setText(mi.getShowtime());		
		if(AppApplication.getInstance().getfMap().containsKey(mi.getId()))
		{
			tv_read.setText("离线阅读");
		}
		
		//============配置ActionBar（可选）=======================================
        String share_content = AppConfig.SHARE_CONTENT.replaceAll("#电影名#", mi.getName());
		UMSocialService controller = UMServiceFactory.getUMSocialService(mi.getId(),RequestType.SOCIAL);
		//设置分享文字
		controller.setShareContent(share_content);
		controller.setShareImage(new UMImage(mContext, mi.getBpic()));

		
		
		
		btn_down.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				if(null!=mi.getComing()&&mi.getComing().equals("1"))
				{
					Toast.makeText(mContext, mi.getComing_time()+"上线,敬请期待哦", Toast.LENGTH_SHORT).show();
				}else{
					
					//把下载信息加入下载数据库
					DownInfo di = new DownInfo();
					di.setMovieid(mi.getId());
					di.setMoviename(mi.getName());
					di.setCurpage(0);
					di.setSize(0);
					Cursor cursor = DBHelper.getInstance(mContext).querySql("select * from downinfo where movieid = ?", new String[]{mi.getId()});
					
					if(null!=cursor&&cursor.getCount()>0)
					{
						Toast.makeText(mContext, "已在下载队列中", Toast.LENGTH_SHORT).show();
					}else{
						long downid = DBHelper.getInstance(mContext).insertDownInfo(di);
						Toast.makeText(mContext, "已加入下载队列", Toast.LENGTH_SHORT).show();
						//加入到下载队列
						AppApplication.getInstance().getDMap().put(di.getMovieid(), di);
						//更新UI
						Intent intent = new Intent(Tag.UPDATEUI);
				        mContext.sendBroadcast(intent);
				        intent = null;
				        //启动下载服务
				        Intent service = new Intent(Tag.START);
						service.putExtra("action", Tag.DownPicList);
						service.putExtra("movieid", mi.getId());
					    mContext.startService(service);	
					    service = null;
					}
					
					if(null!=cursor)
					{
						cursor.close();
						di = null;
					}
				}					
				
			}
		});
		
		
		btn_read.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				if(null!=mi.getComing()&&mi.getComing().equals("1"))
				{
					Toast.makeText(mContext, mi.getComing_time()+"上线,敬请期待哦", Toast.LENGTH_SHORT).show();
				}else{
					Intent introintent = new Intent(mContext,ViewPagerActivity.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("movieinfo", mi);
					introintent.putExtras(bundle);
					mContext.startActivity(introintent);
					introintent = null;
				}
				
			}
		});
		
		btn_mback = (Button)findViewById(R.id.btn_mback);
		btn_mback.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		
		
		
		
		
		
		if(NetworkUtils.getNetworkState(mContext)!=NetworkUtils.NETWORN_NONE)
        {
        	 //社会化分享
            rly_share = (LinearLayout)findViewById(R.id.share_bar);
            //创建ActionBar des参数是ActionBar的唯一标识，请确保不为空
            ActionBarView socializeActionBar = new ActionBarView(mContext,mi.getId());           
            LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
            socializeActionBar.setLayoutParams(layoutParams);
            //添加ActionBar
            rly_share.addView(socializeActionBar);
        }		
	}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			finish();
			break;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	protected static UMSocialService initAcitonBar(Context context, MovieInfo mi) {
		//final ButtonPair mPair = buttonPair;
		UMSocialService controller = UMServiceFactory.getUMSocialService(mi.getId(),
				RequestType.SOCIAL);

		if (!controller.getEntity().initialized) {
			controller.setShareContent(mi.getName());
			controller.initEntity(context, new SocializeClientListener() {
				@Override
				public void onStart() {
				}

				@Override
				public void onComplete(int status, SocializeEntity entity) {
					//matchEntity(mPair, entity);
				}

			});
		} else {
			//matchEntity(mPair, controller.getEntity());
		}
		return controller;
	}
	
	private static byte[] bitmap2Bytes(Bitmap bitmap) {
		ByteArrayOutputStream baos = null;
		if (bitmap == null) return null;
		try {
			baos = new ByteArrayOutputStream();
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
			byte[] b = baos.toByteArray();
			return b;
		} catch (Exception e) {
			if (baos != null) try {
				baos.close();
			} catch (IOException e1) {
			}
		}
		return null;
	}


	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		Logger.error("onPause");
	}


	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
//		Logger.error("onResume");
//		//getIntent().
//		
		Logger.error(((MovieInfo)getIntent().getSerializableExtra("movieinfo")).getName());
		Logger.error("tuijian:"+getIntent().getStringExtra("tuijian"));
//		if(null!=getIntent().getStringExtra("tuijian")&&getIntent().getStringExtra("tuijian").equals("tuijian"))
//		{
//			mi = (MovieInfo)getIntent().getSerializableExtra("movieinfo");
//			if(mi==null)
//			{
//				//Toast.makeText(this, "参数传递错误，请下载最新版本", Toast.LENGTH_SHORT).show();
//				return;
//			}
//			Toast.makeText(this, "参数传递,进行更新", Toast.LENGTH_SHORT).show();
//			
//			fb.display(bPic, mi.getBpic(),640,460);		
//			mIntro.setText(mi.getIntro());		
//			mName.setText(mi.getName());		
//			rBar.setRating(Float.parseFloat(mi.getScore()));		
//			movie_rate.setText(mi.getScore());		
//			mAuthor.setText(mi.getAuthor());		
//			mActor.setText(mi.getActor());		
//			mShowTime.setText(mi.getShowtime());		
//			if(AppApplication.getInstance().getfMap().containsKey(mi.getId()))
//			{
//				tv_read.setText("离线阅读");
//			}
//			
//			//============配置ActionBar（可选）=======================================
//	        String share_content = AppConfig.SHARE_CONTENT.replaceAll("#电影名#", mi.getName());
//			UMSocialService controller = UMServiceFactory.getUMSocialService(mi.getId(),RequestType.SOCIAL);
//			//设置分享文字
//			controller.setShareContent(share_content);
//			controller.setShareImage(new UMImage(mContext, mi.getBpic()));
//		}	
	}

	@Override 
    protected void onNewIntent (Intent intent) 
    { 
         Logger.error("onNewIntent()");
         super.onNewIntent(intent);   
         setIntent(intent);    
         Bundle bundle = intent.getExtras(); 
         if(bundle!=null){ 
             mi = (MovieInfo)getIntent().getSerializableExtra("movieinfo");
             fb.display(bPic, mi.getBpic(),640,460);
             mIntro.setText(mi.getIntro());
             mName.setText(mi.getName());
             rBar.setRating(Float.parseFloat(mi.getScore()));
             movie_rate.setText(mi.getScore());
             mAuthor.setText(mi.getAuthor());
             mActor.setText(mi.getActor());
             mShowTime.setText(mi.getShowtime());
             if(AppApplication.getInstance().getfMap().containsKey(mi.getId()))
              {
                 tv_read.setText("离线阅读");
              }
         } 
    } 
	
	
}
